package com.kedacom.freedomLabel.view.activity.excel;

import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;

import com.github.mjdev.libaums.UsbMassStorageDevice;
import com.github.mjdev.libaums.fs.FileSystem;
import com.github.mjdev.libaums.fs.UsbFile;
import com.github.mjdev.libaums.fs.UsbFileInputStream;
import com.github.mjdev.libaums.partition.Partition;
import com.kedacom.freedomLabel.AppExecutors;
import com.kedacom.freedomLabel.R;
import com.kedacom.freedomLabel.base.BaseActivity;
import com.kedacom.freedomLabel.databinding.ActivityExcelManageBinding;
import com.kedacom.freedomLabel.model.bean.Category;
import com.kedacom.freedomLabel.model.bean.Item;
import com.kedacom.freedomLabel.model.db.AppDatabase;
import com.kedacom.freedomLabel.utils.ExcelImportUtils;
import com.kedacom.freedomLabel.viewmodel.excel.ExcelManageViewModel;
import com.kedacom.lego.annotation.ContentView;
import com.kedacom.lego.annotation.ViewModel;
import com.kedacom.lego.fast.util.ToastUtil;
import com.seray.scaleviewlib.utils.ToastUtils;

import java.util.List;


@ContentView(R.layout.activity_excel_manage)
@ViewModel(ExcelManageViewModel.class)
public class ExcelManageActivity extends BaseActivity<ActivityExcelManageBinding,ExcelManageViewModel> {

    private ProgressDialog importPd;
    private UsbManager mUsbManager;
    private UsbMassStorageDevice[] storageDevices;
    private static final String ACTION_USB_PERMISSION = "com.infol.density.USB_PERMISSION";
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    PendingIntent pendingIntent;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        importPd = new ProgressDialog(this);
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        registerReceiver(usbReceiver, filter);
        pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);

    }

    private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (device != null) {
                            importData();
                        }
                    } else {
                        Log.d("res", "permission denied for device " + device);
                    }
                }
            }
        }
    };

    private void importData() {

        storageDevices = UsbMassStorageDevice.getMassStorageDevices(this);

        if (storageDevices.length <= 0) {
            ToastUtils.showShort("没有发现usb存储设备");
            return;
        }

        if (!checkPerssion(storageDevices[0])) {  //检查是否有权限
            mUsbManager.requestPermission(storageDevices[0].getUsbDevice(), pendingIntent);
            return;
        }

        importPd.setTitle("数据导入中，请稍后...");
        importPd.setCancelable(false);
        importPd.setCanceledOnTouchOutside(false);
        importPd.show();

        AppExecutors.getInstance().insertIO()
                .submit(() -> {
                    try {
                        UsbFile root = readDevice(storageDevices[0]).getRootDirectory();
                        if (root == null) return;
                        UsbFile choiceFile = null;
                        for (UsbFile file : root.listFiles()) {
                            if ("数据导入.xls".equals(file.getName())) {
                                choiceFile = file;
                                break;
                            }
                        }
                        if (choiceFile == null) {
                            ToastUtil.showDefaultToast("未找到数据导入文件。");
                            return;
                        }
                        List<Category> categories = ExcelImportUtils.readCategories(new UsbFileInputStream(choiceFile));
                        List<List<List<Item>>> items = ExcelImportUtils.readItemList(new UsbFileInputStream(choiceFile), categories);
/*                        File choiceFile = new File(Environment.getExternalStorageDirectory(), "数据导入.xls");
                        if (!choiceFile.exists()) {
                            ToastUtil.showDefaultToast("未找到数据导入文件。");
                            return;
                        }

                        List<Category> categories = ExcelImportUtils.readCategories(choiceFile);
                        List<List<List<Item>>> items = ExcelImportUtils.readItemList(choiceFile, categories);*/

                        AppDatabase.getInstance().runInTransaction(() -> {
                            try {
                                // 清空categories数据
                                AppDatabase.getInstance().categoryDao().delete();
                                //清空item数据
                                AppDatabase.getInstance().itemDao().delete();
                                //创建categories数据
                                AppDatabase.getInstance().categoryDao().save(categories);
                                // 创建Item数据
                                for (int i = 0; i < items.size(); i++) {
                                    List<List<Item>> temp = items.get(i);
                                    Category category = categories.get(i);

                                    for (List<Item> itemList : temp) {
                                        for (Item item : itemList) {
//                                            item.parent = category.uuid;
                                        }
                                        AppDatabase.getInstance().itemDao().save(itemList);
                                    }
                                }
                                importSuccess();
                            } catch (Exception e) {
                                importFail("导入失败，请检查数据的合法性。");
                                throw e;
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        importFail("导出失败，请重新拔插usb设备。");
                    }

                });
    }
    /**
     * 检查usb设备的权限
     *
     * @param device
     * @return
     */
    public boolean checkPerssion(UsbMassStorageDevice device) {
        if (mUsbManager == null) {
            return false;
        }
        if (mUsbManager.hasPermission(device.getUsbDevice())) {//有就直接读取设备是否有权限
            return true;
        } else {
            return false;
        }
    }
    private void importFail(String msg) {
        runOnUiThread(() -> {
            if (importPd != null && importPd.isShowing())
                importPd.dismiss();
            ToastUtils.showLong(msg);
        });
    }

    private void importSuccess() {
        runOnUiThread(() -> {
            if (importPd != null && importPd.isShowing())
                importPd.dismiss();
            ToastUtils.showLong("导入成功");
        });
    }

    /**
     * 根据设备获取路径
     *
     * @param device
     * @return
     */
    public FileSystem readDevice(UsbMassStorageDevice device) {
        try {

            if (!checkPerssion(device)) {  //检查是否有权限
                mUsbManager.requestPermission(device.getUsbDevice(), pendingIntent);
                return null;
            }

            device.init();//使用设备之前需要进行 初始化
            Partition partition = device.getPartitions().get(0); //仅使用设备的第一个分区
            FileSystem currentFs = partition.getFileSystem();
            // currentFs.getCapacity(); //容量大小
            // currentFs.getOccupiedSpace(); //已使用大小
            // currentFs.getFreeSpace();  //未使用的大小
            UsbFile root = currentFs.getRootDirectory();//获取根目录
            String deviceName = currentFs.getVolumeLabel();//获取设备标签
            return currentFs;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
